package com.hxqh.bo.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hxqh.bo.bean.FpsUserFundInfo;
import com.hxqh.bo.dao.FpsUserFundInfoDAO;

/**
 * A data access object (DAO) providing persistence and search support for
 * FpsUserFundInfo entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see com.hxqh.bo.bean.FpsUserFundInfo
 * @author MyEclipse Persistence Tools
 */

public class FpsUserFundInfoDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(FpsUserFundInfoDAO.class);
	// property constants
	public static final String ORDER_REF = "orderRef";
	public static final String USER_ID = "userId";
	public static final String POLICY_ID = "policyId";
	public static final String POLICY_NAME = "policyName";
	public static final String FUTURES_CODE = "futuresCode";
	public static final String TRADE_NUM = "tradeNum";
	public static final String OPEN_PRICE = "openPrice";
	public static final String CLOSE_PRICE = "closePrice";
	public static final String FUND_FLOAT = "fundFloat";
	public static final String PROFIT_LOST = "profitLost";
	public static final String SELL = "sell";
	public static final String AUTOMATIC = "automatic";

	protected void initDao() {
		// do nothing
	}
	
	public List getUserFundList(final String userId, final String appendSQL) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				
				String sql = "select AUTOMATIC,ORDER_REF,POLICY_NAME,FUTURES_CODE," +
						" SELL,SUM(TRADE_NUM) TRADE_NUM,avg(OPEN_PRICE) OPEN_PRICE," +
						" avg(CLOSE_PRICE) CLOSE_PRICE,TRADE_DATE,SUM(PROFIT_LOST) PROFIT_LOST," +
						" sum(FUND_FLOAT) FUND_FLOAT" +
						" from fps_user_fund_info" +
						" where user_id = " + userId + " " + appendSQL +
						" group by TRADE_DATE,POLICY_NAME" +
						" ORDER BY TRADE_DATE desc";
				SQLQuery q = arg0.createSQLQuery(sql);
				q.addScalar("AUTOMATIC",Hibernate.INTEGER);
				q.addScalar("ORDER_REF",Hibernate.LONG);
				q.addScalar("POLICY_NAME",Hibernate.STRING);
				q.addScalar("FUTURES_CODE",Hibernate.STRING);
				q.addScalar("SELL",Hibernate.INTEGER);
				q.addScalar("TRADE_NUM",Hibernate.INTEGER);
				q.addScalar("OPEN_PRICE",Hibernate.DOUBLE);
				q.addScalar("CLOSE_PRICE",Hibernate.DOUBLE);
				q.addScalar("TRADE_DATE",Hibernate.TIMESTAMP);
				q.addScalar("PROFIT_LOST",Hibernate.DOUBLE);
				q.addScalar("FUND_FLOAT",Hibernate.DOUBLE);
				return q.list();
			}
		});
	}
	
	public Double getLastFundFloatByPolicyId(final Integer policyId,
			final Integer userId, final String futuresCode, final Integer sell) {
		Double fund = (Double) getHibernateTemplate().execute(
				new HibernateCallback() {
					@Override
					public Object doInHibernate(Session arg0)
							throws HibernateException, SQLException {
						// TODO Auto-generated method stub
						String sql = "select FUND_FLOAT from fps_user_fund_info where USER_FUND_ID = " +
								"(select max(b.USER_FUND_ID) from fps_user_fund_info b" +
								" where b.POLICY_ID=" + policyId + 
								" and b.USER_ID=" + userId +
								" and b.FUTURES_CODE='" + futuresCode +
								"' and b.SELL=" + sell +
								"  )";
						SQLQuery q = arg0.createSQLQuery(sql);
						q.addScalar("fund_float", Hibernate.DOUBLE);
						return q.uniqueResult();
					}
				});

		return fund!=null?fund:new Double(0);
	}

	public void save(FpsUserFundInfo transientInstance) {
		log.debug("saving FpsUserFundInfo instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(FpsUserFundInfo persistentInstance) {
		log.debug("deleting FpsUserFundInfo instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public FpsUserFundInfo findById(java.lang.Integer id) {
		log.debug("getting FpsUserFundInfo instance with id: " + id);
		try {
			FpsUserFundInfo instance = (FpsUserFundInfo) getHibernateTemplate()
					.get("com.hxqh.bo.bean.FpsUserFundInfo", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(FpsUserFundInfo instance) {
		log.debug("finding FpsUserFundInfo instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding FpsUserFundInfo instance with property: "
				+ propertyName + ", value: " + value);
		try {
			String queryString = "from FpsUserFundInfo as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByOrderRef(Object orderRef) {
		return findByProperty(ORDER_REF, orderRef);
	}

	public List findByUserId(Object userId) {
		return findByProperty(USER_ID, userId);
	}

	public List findByPolicyId(Object policyId) {
		return findByProperty(POLICY_ID, policyId);
	}

	public List findByPolicyName(Object policyName) {
		return findByProperty(POLICY_NAME, policyName);
	}

	public List findByFuturesCode(Object futuresCode) {
		return findByProperty(FUTURES_CODE, futuresCode);
	}

	public List findByTradeNum(Object tradeNum) {
		return findByProperty(TRADE_NUM, tradeNum);
	}

	public List findByOpenPrice(Object openPrice) {
		return findByProperty(OPEN_PRICE, openPrice);
	}

	public List findByClosePrice(Object closePrice) {
		return findByProperty(CLOSE_PRICE, closePrice);
	}

	public List findByFundFloat(Object fundFloat) {
		return findByProperty(FUND_FLOAT, fundFloat);
	}

	public List findByProfitLost(Object profitLost) {
		return findByProperty(PROFIT_LOST, profitLost);
	}

	public List findBySell(Object sell) {
		return findByProperty(SELL, sell);
	}

	public List findByAutomatic(Object automatic) {
		return findByProperty(AUTOMATIC, automatic);
	}

	public List findAll() {
		log.debug("finding all FpsUserFundInfo instances");
		try {
			String queryString = "from FpsUserFundInfo";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public FpsUserFundInfo merge(FpsUserFundInfo detachedInstance) {
		log.debug("merging FpsUserFundInfo instance");
		try {
			FpsUserFundInfo result = (FpsUserFundInfo) getHibernateTemplate()
					.merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(FpsUserFundInfo instance) {
		log.debug("attaching dirty FpsUserFundInfo instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(FpsUserFundInfo instance) {
		log.debug("attaching clean FpsUserFundInfo instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static FpsUserFundInfoDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (FpsUserFundInfoDAO) ctx.getBean("FpsUserFundInfoDAO");
	}
}